<style scoped>
 .img{
   width: 150px;
   height: 100px;
   float: left;
   margin: 5px;
 }
 .img-click{
   width: 150px;
   height: 100px;
   float: left;
   margin: 5px;
   border: 1px solid blue;
 }
.img:hover {
  border: 1px solid blue;
}
.img-btn {
  clear:both;
  float: right;
  margin-right: 85px;
}
.btn-left {
  float:left;
  padding:5px 10px;
  /* margin-right: 650px; */
  /* margin-top: -100px; */
}
.btn-right {
  float: right;
  padding:5px 10px;
  margin-right: -50px;
  /* margin-top: -100px; */
}
.outer {
  position: relative;
  height: 460px;
}
.toolbar {
  width: 100%;
  /* border: 1px solid #ccc; */
  position: relative;
  z-index: 125;
}
.text {
  border: 1px solid #ccc;
  /* min-height: 400px; */
  height: 400px;
}
.boxerl {
  position: relative;
  width: 100%;
  overflow-x: hidden;
  overflow-y: hidden;
  height: 320px;
}
.boxerh {
  z-index: 120;
  top: 66px;
  position: absolute;
  width: 100%;
  height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
}
.scollbar {
  width: 100%;
  overflow-x: auto;
}
.blankinner {
  width: 768px;
  height: 5px;
  border: 1px solid white;
}
</style>
<template>
  <div>
    <Modal
      :value="modalState"
      :title="title"
      :loading="loading"
      ok-text="保存"
      @on-ok="handleSubmit"
      @on-cancel="cancel"
      width="60%">
      <Form
        ref="taskListEditModal"
        :model="row"
        :rules="ruleInline"
        style="width: 100%"
        :label-width="200">
        <!-- <FormItem prop="type" label="类型：" style="width: 500px">
          <RadioGroup v-model="row.type">
            <Radio label="产品"></Radio>
            <Radio label="活动推广"></Radio>
            <Radio label="销售素材"></Radio>
          </RadioGroup>
        </FormItem> -->
        <FormItem prop="type" label="结算方式：" style="width: 500px">
          <RadioGroup v-model="row.type">
            <Radio label="3" :disabled="row.state === 1">口碑结算</Radio>
            <Radio label="1" :disabled="row.state === 1">到店结算</Radio>
            <Radio label="2" :disabled="row.state === 1">成交结算</Radio>
            <!-- <Radio label="4" :disabled="row.state === 1">销售素材</Radio> -->
          </RadioGroup>
        </FormItem>
        <div v-show="row.type">
          <div v-show="row.type !== '4'">
          <FormItem prop="time" label="活动时间：" style="width: 1000px">
            <DatePicker :disabled="row.state === 1" v-model="row.time" format="yyyy-MM-dd" type="daterange" placeholder="请选择活动时间" @on-change="handleChange"></DatePicker>
            <!-- <DatePicker v-model="row.startTime" type="date" placeholder="请输入开始时间"></DatePicker>
            <DatePicker v-model="row.endTime" type="date" placeholder="请输入结束时间"></DatePicker> -->
          </FormItem>
          <FormItem prop="name" label="任务名称：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.name" placeholder="请输入任务名称(30字以内)" :maxlength="30" />
          </FormItem>
          <FormItem prop="subtitle" label="副标题名称：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.subtitle" placeholder="请输入副标题名称(30字以内)" :maxlength="30" />
          </FormItem>
          <FormItem prop="des" label="任务要求：" style="width: 95%">
            <!-- <Input :disabled="row.state === 1" v-model="row.des" type="textarea" placeholder="请输入任务要求" /> -->
            <!-- <div ref="editor" style="text-align:left;">
            </div> -->
            <div class="outer">
              <div id="scoller" class="scollbar" @scroll="doThis()">
                <div class="blankinner"></div>
              </div>
              <div id="inner" class="boxerl">
                <div id="div1" class="toolbar">
                  <Button :disabled="row.state === 1" icon="md-trash" size="large" style="border: none; margin-top: -3px" @click="handleClear"></Button>
                </div>
              </div>
              <!--<div style="padding: 5px 0; color: #ccc">menu list</div>-->
              <div class="boxerh">
                <div id="div2" class="text">
                  <!--可使用 min-height 实现编辑区域自动增加高度-->
                  <!-- <p>请输入内容</p> -->
                </div>
              </div>
            </div>
          </FormItem>
          <FormItem v-show="row.type === '3'" prop="permoney" label="单个点击积分：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.permoney" placeholder="请输入积分" />
          </FormItem>
          <FormItem v-if="row.type === '3'" prop="budget" label="预算积分：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.budget" placeholder="请输入预算积分" />
          </FormItem>
          <FormItem v-if="row.type === '1'" prop="permoney" label="任务积分：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.permoney" placeholder="请输入到店积分：如100" />
          </FormItem>
          <FormItem v-show="row.type === '2'" prop="permoney" label="成交商品价格：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.permoney" placeholder="请输入成交商品积分" />
          </FormItem>
          <FormItem v-if="row.type === '2'" prop="perrate" label="任务积分(%)：" style="width: 400px">
            <Row>
              <Col span="16">
                <Input :disabled="row.state === 1" type="text" v-model=" row.perrate" placeholder="请输入任务积分：如1" />
              </Col>
              <Col span="5">
                %
              </Col>
            </Row>
          </FormItem>
          </div>
          <div v-show="row.type === '4'">
            <FormItem prop="name" label="任务名称：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.name" placeholder="请输入任务名称(30字以内)" :maxlength="30" />
          </FormItem>
          <FormItem prop="subtitle" label="副标题名称：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.subtitle" placeholder="请输入副标题名称(30字以内)" :maxlength="30" />
          </FormItem>
          </div>
          <FormItem prop="tctype" label="内容类型：" style="width: 500px">
            <RadioGroup v-model="row.tctype" @on-change="changeContent">
              <!-- <Radio :disabled="row.state === 1" label="0">H5</Radio> -->
              <Radio :disabled="row.state === 1" label="1">图文</Radio>
              <Radio :disabled="row.state === 1" label="2">视频</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="当前关联内容：" v-show="row.id">
            <div v-show="row.tctype === '0' && row.id">
              <div style="text-align: center; width: 150px; height: 50px;">
                {{row.cname}}
              </div>
              <img :src="row.tcimg ? row.host+row.tcimg : ''" alt="" style="width: 150px; height: 100px; float: left; margin: 5px;">
            </div>
            <div v-show="row.tctype === '1' && row.id">
              <div style="text-align: center; width: 150px; height: 50px;">
                {{row.cname}}
              </div>
              <img :src="row.tcimg ? row.host+row.tcimg : ''" alt="" style="width: 150px; height: 100px; float: left; margin: 5px;">
            </div>
            <div v-show="row.tctype === '2' && row.id">
              <div style="text-align: center; width: 150px; height: 50px;">
                {{row.cname}}
              </div>
              <img :src="row.tcimg ? row.host+row.tcimg : ''" alt="" style="width: 150px; height: 100px; float: left; margin: 5px;">
            </div>
          </FormItem>
          <FormItem v-show="row.tctype" prop="img" label="选择关联内容：">
            <!-- <div v-show="!row.id">
              单击图片选择，双击图片预览
            </div> -->
            <div v-show="row.tctype === '0' && (!row.id || row.state === 0)">
              <div>
                <div style="width: 150px; height: 100%; float: left; margin: 5px;" :key="index" v-for="(item, index) in imgHistoryData" >
                  <div style="text-align: center; width: 150px; height: 50px;">
                    {{item.name}}
                  </div>
                  <img ref="img" style="width: 150px; height: 100px; float: left;" :key="index"  :src="item.img ? item.host+item.img : ''" :alt="item.name" :class="{'img-click':ind === index}" @click="clickImg(item, index)"/>
                </div>
              </div>
              <div class="img-btn" v-show="imgHistoryData.length !== 0 && imgHistoryData.length > 8">
                <Button type="primary" :disabled="preDisabled" ghost @click="previousPage" class="btn-left">{{leftBtn}}</Button>
                <!-- <div style="width: 100%">第{{currentPage}}页</div> -->
                <Button type="primary" :disabled="disabled" ghost  @click="nextPage" class="btn-right">></Button>
              </div>
            </div>
            <div v-show="row.tctype === '1' && (!row.id || row.state === 0)">
              <div>
                <div v-for="(item, index) in twHistoryData" :key="index" style="width: 150px; height: 100%; float: left; margin: 5px; margin-bottom: 28px">
                  <div style="text-align: center; width: 150px; height: 50px;">
                    {{item.name}}
                  </div>
                  <img ref="tw" style="width: 150px; height: 100px; float: left; margin: 5px;" :key="index" :src="item.img ? item.host+item.img : ''" alt="" :class="{'img-click':twInd === index}" @click="clickTw(item, index)">
                </div>
              </div>
              <div class="img-btn" v-show="twHistoryData.length !== 0 && twHistoryData.length > 0">
                <!-- <table-page
                  class="paging"
                  :dataCount="dataCount"
                  @change-page="changePage"
                  @change-page-size="changePageSize"
                  :pageSize="pageSize">
                </table-page> -->
                <Button type="primary" :disabled="preDisabled" ghost @click="previousPage" class="btn-left">{{leftBtn}}</Button>
                <!-- <div style="width: 100%;">第{{currentPage}}页</div> -->
                <Button type="primary" :disabled="disabled" ghost  @click="nextPage" class="btn-right">></Button>
              </div>
            </div>
            <div v-show="row.tctype === '2' && (!row.id || row.state === 0)">
              <div v-for="(item, index) in videoHistoryData" style="width: 150px; height: 100%; float: left; margin: 5px;" :key="index">
                <div style="text-align: center; width: 150px; height: 50px;">
                  {{item.name}}
                </div>
                <img ref="video" style="width: 150px; height: 100px; float: left; margin: 5px;" :key="index"  :src="item.img ? item.host+item.img : ''" :alt="item.name" :class="{'img-click':videoInd === index}" @click="clickVideo(item, index)"/>
              </div>
              <div class="img-btn"  v-show="videoHistoryData.length !== 0 && videoHistoryData.length > 8">
                <!-- <table-page
                  class="paging"
                  :dataCount="dataCount"
                  @change-page="changePage"
                  @change-page-size="changePageSize"
                  :pageSize="pageSize">
                </table-page> -->
                <Button type="primary" :disabled="preDisabled" ghost @click="previousPage" class="btn-left">{{leftBtn}}</Button>
                <!-- <div style="width: 100%">第{{currentPage}}页</div> -->
                <Button type="primary" :disabled="disabled" ghost  @click="nextPage" class="btn-right">></Button>
              </div>
            </div>
          </FormItem>
          <FormItem prop="sort" label="排序：" style="width: 400px">
            <Input :disabled="row.state === 1" type="text" v-model="row.sort" placeholder="请输入排序序号" />
          </FormItem>
          <FormItem prop="top" label="是否置顶：">
            <i-switch :disabled="row.state === 1" v-model="row.strickState" />
          </FormItem>
          <FormItem prop="openState" label="是否开启：">
            <i-switch :disabled="row.state === 1" v-model="row.openState" />
          </FormItem>
        </div>
      </Form>
    </Modal>
  </div>
</template>
<script>
import {
  mapActions,
  mapState
} from 'vuex'
import TablePage from '_c/table-page'
import { getToken } from '../../libs/util'
import E from 'wangeditor'
export default {
  name: 'TaskListEditModal',
  components: {
    TablePage
  },
  data () {
    const reg = /^\d+$/
    const validateDate = (rule, value, callback) => {
      const start = value[0]
      const end = value[1]
      if (start === '' && end === '') {
        callback(new Error('请选择活动时间！'))
      } else {
        callback()
      }
    }

    const validateScore = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('积分不能为空!'))
      } else {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的积分！'))
        } else {
          callback()
        }
      }
    }
    return {
      index: '',
      ind: '',
      editorContent: '',
      twInd: '',
      videoInd: '',
      title: '',
      leftBtn: '<',
      token: getToken(),
      page: 1,
      disabled: false,
      preDisabled: true,
      cid: '',
      value: '',
      loading: true,
      form: {
        time: '',
        type: '',
        method: '',
        task: '',
        title: '',
        taskmoney: '',
        order: '',
        state: ''
      },
      // row: {
      //   id: '',
      //   time: '',
      //   ctime: '',
      //   btime: '',
      //   etime: '',
      //   type: '',
      //   name: '',
      //   des: '',
      //   budget: '',
      //   traffic: '',
      //   contentType: '',
      //   sticky: false,
      //   state: false,
      //   permoney: '',
      //   perrate: '',
      //   sort: ''
      // },
      ruleInline: {
        time: [
          {
            validator: validateDate,
            trigger: 'change'
          }
        ],
        name: [
          {
            required: true,
            message: '任务名称不能为空',
            trigger: 'blur'
          }
        ],
        permoney: [
          {
            validator: validateScore,
            trigger: 'blur'
          }
        ],
        budget: [
          {
            validator: validateScore,
            trigger: 'blur'
          }
        ],
        tctype: [
          {
            required: true,
            message: '请选择内容类型',
            trigger: 'change'
          }
        ],
        perrate: [
          {
            validator: validateScore,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  updated () {
    // console.log(this.row.id)
    if (this.row.id && this.row.id !== '') {
      this.title = '编辑任务'
    } else {
      this.title = '添加任务'
    }
  },
  computed: {
    ...mapState({
      taskList: state => state.taskList.taskList,
      row: state => state.taskList.row,
      modalState: state => state.modal.modalState,
      dataCount: state => state.taskList.taskListDataCount,
      imgHistoryData: state => state.h5Content.imgHistoryData,
      twHistoryData: state => state.graphic.twHistoryData,
      videoHistoryData: state => state.video.taskVideoHistoryData,
      pageSize: state => state.taskList.imgPageSize,
      currentPage: state => state.taskList.currentPage
    })
  },
  methods: {
    ...mapActions([
      'updateModalState',
      'changeImgPage',
      'changeTwPage',
      'changeVideoPage',
      'changeCurrentPage',
      'getH5List',
      'getGraphicList',
      'getVideoList'
    ]),
    changeLoading () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    handleClear () {
      this.editor.txt.clear()
    },
    doThis () {
      var elem = document.getElementById('scoller')
      var inner = document.getElementById('inner')
      inner.scrollLeft = elem.scrollLeft
    },
    handleSubmit () {
      this.$refs.taskListEditModal.validate((valid) => {
        if (!valid) {
          return this.changeLoading()
        }
        this.$emit('edit-task-list-valid', {
          taskListEditModal: this.$refs['taskListEditModal'],
          currentImg: this.$refs['img'],
          currentTw: this.$refs['tw'],
          currentIndex: this.index ? this.index : '',
          currentPage: this.page,
          disabled: this.disabled,
          preDisabled: this.preDisabled,
          id: this.row.id ? this.row.id : '',
          // time: '',
          // ctime: '',
          cid: this.cid,
          btime: this.row.time ? this.row.time[0] : '',
          etime: this.row.time ? this.row.time[1] : '',
          type: this.row.type,
          name: this.row.name,
          des: this.editorContent ? this.editorContent : this.row.des,
          budget: this.row.budget,
          traffic: this.row.traffic,
          tctype: this.row.tctype,
          strickState: this.row.strickState,
          top: this.row.strickState === true ? 'true' : 'false',
          openState: this.row.openState,
          state: this.row.openState === true ? 1 : 0,
          permoney: this.row.permoney,
          perrate: this.row.perrate,
          sort: this.row.sort,
          subtitle: this.row.subtitle,
          img: this.row.img
          // id: this.row.id ? this.row.id : '',
          // time: this.row.time ? this.row.time : '',
          // startTime: this.row.time ? this.row.time[0] : '',
          // endTime: this.row.time ? this.row.time[1] : '',
          // // type: this.row.type,
          // method: this.row.method,
          // task: this.row.task,
          // taskRequire: this.row.taskRequire,
          // budget: this.row.budget,
          // traffic: this.row.traffic,
          // contentType: this.row.contentType,
          // sticky: this.row.sticky,
          // img: this.row.img,
          // // open: this.row.open,
          // missionMoney: this.row.missionMoney,
          // price: this.row.price,
          // commision: this.commision,
          // title: this.row.title,
          // taskmoney: this.row.taskmoney,
          // order: this.row.order,
          // state: this.row.state
        })
        // this.$refs['taskListEditModal'].resetFields()
      })
    },
    cancel () {
      this.updateModalState(false)
      this.$refs['taskListEditModal'].resetFields()
      // if(this.index !=='') {
      //   this.$refs['img'][this.index].className = 'img'
      //   this.$refs['tw'][this.index].className = 'img'
      // }
      this.page = 1
      // this.changeImgPage(this.page)
      this.changeCurrentPage(this.page)
      this.changeImgPage(this.currentPage)
      this.disabled = false
      this.preDisabled = true
      // this.page = 1
      // this.changePage(this.page)
      // ////console.log(this.page)
    },
    handleChange (value) {
      this.row.time = value
    },
    clickImg (item, index) {
      this.ind = index
      // //console.log(item)
      this.cid = item.id
      this.index = index
      // //console.log(this.$refs['img'][0])
      // this.$refs['img'][index].className = 'img-click'
      this.row.img = item.img
    },
    clickTw (item, index) {
      this.twInd = index
      this.index = index
      this.cid = item.id
      // //console.log(this.$refs['tw'][0])
      // this.$refs['tw'][index].className = 'img-click'
      this.row.img = item.img
    },
    clickVideo (item, index) {
      this.videoInd = index
      this.index = index
      this.cid = item.id
      // //console.log(this.$refs['video'][0])
      // this.$refs['video'][index].className = 'img-click'
      this.row.img = item.img
    },
    // changePage (index) {
    //   // this.page = index
    //   this.changeImgPage(index)
    // },
    changeContent (value, index) {
      // console.log(value)
      this.value = value
      // //console.log(value)
      if (this.index !== '') {
        index = this.index
        this.$refs['img'][this.index].className = 'img'
        this.$refs['tw'][this.index].className = 'img'
        this.$refs['video'][this.index].className = 'img'
      }
    },
    nextPage () {
      if (this.currentPage < Math.ceil(this.dataCount / this.pageSize)) {
        this.page += 1
        // this.changeImgPage(this.page)
        this.changeCurrentPage(this.page)
        // console.log(this.value)
        if (this.value === '0' || this.row.tctype === '0') {
          this.changeImgPage(this.currentPage).then(
            this.getH5List({
              type: 0,
              page: this.currentPage,
              rows: 8
            })
          )
        } else if (this.value === '1' || this.row.tctype === '1') {
          this.changeTwPage(this.currentPage).then(
            this.getGraphicList({
              type: 1,
              page: this.currentPage,
              rows: 8
            })
          )
        } else if (this.value === '2' || this.row.tctype === '2') {
          this.changeVideoPage(this.currentPage).then(
            this.getVideoList({
              type: 2,
              page: this.currentPage,
              rows: 8
            })
          )
        }
      }
      if (this.currentPage > this.dataCount / this.pageSize) {
        this.disabled = true
      }
      if (this.currentPage > 1) {
        this.preDisabled = false
      }
      // this.page = index
    },
    previousPage () {
      if (this.currentPage > 1) {
        this.preDisabled = false
        this.disabled = false
        this.page -= 1
        // this.changeImgPage(this.page)
        this.changeCurrentPage(this.page)
        if (this.value === '0' || this.row.tctype === '0') {
          this.changeImgPage(this.currentPage).then(
            this.getH5List({
              type: 0,
              page: this.currentPage,
              rows: 8
            })
          )
        } else if (this.value === '1' || this.row.tctype === '1') {
          this.changeTwPage(this.currentPage).then(
            this.getGraphicList({
              type: 1,
              page: this.currentPage,
              rows: 8
            })
          )
        } else if (this.value === '2' || this.row.tctype === '2') {
          this.changeVideoPage(this.currentPage).then(
            this.getVideoList({
              type: 2,
              page: this.currentPage,
              rows: 8
            })
          )
        }
      }
      if (this.currentPage < 2) {
        this.preDisabled = true
      }
      // this.page = index
    }
  },
  created () {
    window.addEventListener('scroll', this.doThis)
  },
  mounted () {
    let self = this
    // //console.log(this.graphicList)
    this.actionUrl = process.env.NODE_ENV === 'development' ? '/api/upload?folder=task' : 'http://rbackapi.baisha.work/upload?folder=task'
    this.editor = new E('#div1', '#div2')
    // this.editor = new E(this.$refs.editor)
    this.editor.customConfig.onchange = (html) => {
      this.editorContent = html
      // this.$refs.showContent.innerHTML = html
    }
    // //console.log(this.row.content)
    // editor.customConfig.uploadImgShowBase64 = true
    this.editor.customConfig.withCredentials = true
    // this.editor.customConfig.debug = true
    this.editor.customConfig.uploadImgServer = this.actionUrl
    this.editor.customConfig.uploadImgMaxSize = 500 * 1024
    this.editor.customConfig.uploadImgHeaders = {
      'agent': 'Web',
      'token': this.token
    }
    // editor.customConfig.uploadImgParams = {
    //   // 如果版本 <=v3.1.0 ，属性值会自动进行 encode ，此处无需 encode
    //   // 如果版本 >=v3.1.1 ，属性值不会自动 encode ，如有需要自己手动 encode
    //   token: 'abcdef12345'
    // }
    this.editor.customConfig.uploadImgHooks = {
      before (xhr, editor, files) {
        // 图片上传之前触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件

        // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
        // return {
        //     prevent: true,
        //     msg: '放弃上传'
        // }
      },
      success (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
        // //console.log(editor)
        // //console.log(result)
      },
      fail (xhr, editor, result) {
        this.$Notice.warning({
          title: '文件大小不正确',
          desc: '请上传3M以下大小的图片'
        })
        // 图片上传并返回结果，但图片插入错误时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
      },
      error (xhr, editor) {
        // 图片上传出错时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },
      timeout (xhr, editor) {
        // 图片上传超时时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },

      // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
      // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
      customInsert (insertImg, result, editor) {
        // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
        // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

        // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
        let url = result.host + result.data
        insertImg(url)
        // result 必须是一个 JSON 格式字符串！！！否则报错
      }
    }
    this.editor.customConfig.customAlert = function (info) {
      // info 是需要提示的内容
      self.$Notice.warning({
        title: '文件大小不正确',
        desc: '请上传500kb以下大小的图片'
      })
    }
    this.editor.create()
    this.editor.customConfig.pasteFilterStyle = false
    this.editor.txt.html(this.row.des)
    if (this.row.state === 1) {
      this.editor.$textElem.attr('contenteditable', false)
    }
  }
}
</script>
